import struct
from utils import GxRawStream

class GxParameter(object):
    def device(self):
        return DevicePoints(self)

    def read(self, stream):
        self.header = stream.read(0x40)
        self.body = {}
        while True:
            data = stream.readDataBlock()
            if not data:
                break
            datatype = struct.unpack("H", data[:2])[0]
            self.body[datatype] = data[2:]
            
    def write(self, stream):
        stream.write(self.header)
        datatypes = sorted(self.body.keys())
        for datatype in datatypes:
            stream.write(struct.pack("H", datatype))
            stream.write(self.body[datatype])
        stream.write("\xff\xff") # end block
                
                
class DevicePoints(dict):
    def __init__(self, parameter):
        self.parameter = parameter
        dict.__init__(self)
        
        content = GxRawStream(self.parameter.body[0x2000])
        count = content.readint("H")
        for i in range(count):
            device  = content.readint("B")
            kilo = content.readint("B")
            count = content.readint("H")
            self[device] = (kilo, count)
        